﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace TryWebListener
{
	public class Program
	{
		private void Run(string[] args)
		{
			try
			{
				Socket listenSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

				IPAddress  host = IPAddress.Loopback;
				IPEndPoint endP = new IPEndPoint(host, 9898);
				listenSock.Bind(endP);

				listenSock.Listen(1);

				Socket acceptSock = listenSock.Accept();

				NetworkStream netStream = new NetworkStream(acceptSock);
				
				List<byte> byteList = new List<byte>();
				byte[] buffer = new byte[1024];
				int read = 0;
				do
				{
					read = netStream.Read(buffer, 0, buffer.Length);
					if (read == buffer.Length)
					{
						byteList.AddRange(buffer);
					}
					else
					{
						for (int i = 0; i < read; i++)
						{
							byteList.Add(buffer[i]);
						}
					}
				} while (read == buffer.Length);

				string retVal = Encoding.UTF8.GetString(byteList.ToArray());
			}
			catch (Exception err)
			{
				Console.Error.WriteLine("Exception Details:\n{0}", err.ToString());
			}
		}

		public static void Main(string[] args)
		{
			Program program = new Program();
			program.Run(args);

			Console.Out.WriteLine("Press [ENTER] to quit...");
			Console.In.ReadLine();
		}
	}
}
